<template>
  <div class="container">
    <div class="card">
      <div class="card-header">
        <h2>编辑投资记录</h2>
      </div>
      <div class="card-body">
        <!-- 加载中 -->
        <div v-if="loading">
          <loading-spinner size="large" message="加载中..." />
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="alert alert-danger mb-4">
          {{ error }}
        </div>
        
        <!-- 表单 -->
        <form v-if="!loading && investment && !transactionSuccess" @submit.prevent="submitForm">
          <div class="mb-3">
            <label for="id" class="form-label">投资ID</label>
            <input
              type="text"
              class="form-control"
              id="id"
              :value="id"
              disabled
            >
            <div class="form-text text-muted">投资ID不可修改</div>
          </div>
          
          <div class="mb-3">
            <label for="amount" class="form-label">投资金额 <span class="text-danger">*</span></label>
            <input 
              type="number" 
              class="form-control" 
              id="amount" 
              v-model="form.amount" 
              required 
              min="1"
              placeholder="请输入投资金额（整数）"
            >
          </div>
          
          <div class="mb-3">
            <label for="projectName" class="form-label">项目名称 <span class="text-danger">*</span></label>
            <input 
              type="text" 
              class="form-control" 
              id="projectName" 
              v-model="form.projectName" 
              required 
              maxlength="50"
              placeholder="请输入投资项目名称"
            >
          </div>
          
          <div class="mb-3">
            <label for="profession" class="form-label">所属行业 <span class="text-danger">*</span></label>
            <select 
              class="form-select" 
              id="profession" 
              v-model="form.profession" 
              required
            >
              <option value="" disabled>请选择行业</option>
              <option value="金融">金融</option>
              <option value="科技">科技</option>
              <option value="医疗">医疗</option>
              <option value="教育">教育</option>
              <option value="能源">能源</option>
              <option value="制造">制造</option>
              <option value="房地产">房地产</option>
              <option value="其他">其他</option>
            </select>
          </div>
          
          <div class="mb-3">
            <label class="form-label">区块链信息</label>
            <div class="card bg-light">
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6">
                    <p><strong>投资者地址:</strong><br />
                      <hash-display :value="investment.investor" :shorten="true" />
                    </p>
                  </div>
                  <div class="col-md-6">
                    <p><strong>数据哈希:</strong><br />
                      <hash-display :value="investment.dataHash" :shorten="true" />
                    </p>
                  </div>
                </div>
                <div class="alert alert-info">
                  <i class="bi bi-info-circle me-2"></i>
                  更新后，系统将生成新的数据哈希并记录到区块链上
                </div>
              </div>
            </div>
          </div>
          
          <div class="d-flex justify-content-between mt-4">
            <router-link :to="`/detail/${id}`" class="btn btn-secondary">
              <i class="bi bi-arrow-left"></i> 返回
            </router-link>
            <button type="submit" class="btn btn-primary" :disabled="!isFormValid || submitting">
              <span v-if="submitting">
                <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                处理中...
              </span>
              <span v-else>
                <i class="bi bi-check-circle"></i> 保存修改
              </span>
            </button>
          </div>
        </form>
        
        <!-- 交易成功提示 -->
        <div v-if="transactionSuccess" class="alert alert-success mt-4">
          <h4 class="alert-heading">投资记录更新成功！</h4>
          <p>您的投资记录已成功更新并提交到区块链。</p>
          <hr>
          <p class="mb-0">
            <strong>投资ID:</strong> {{ id }}<br>
            <strong>交易哈希:</strong> <hash-display :value="transactionHash" /><br>
            <strong>区块号:</strong> {{ blockNumber }}
          </p>
          <div class="mt-3">
            <router-link :to="`/detail/${id}`" class="btn btn-info me-2">
              查看详情
            </router-link>
            <router-link to="/" class="btn btn-primary">
              返回首页
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import LoadingSpinner from '@/components/LoadingSpinner.vue';
import HashDisplay from '@/components/HashDisplay.vue';

export default {
  name: 'EditInvestmentView',
  components: {
    LoadingSpinner,
    HashDisplay
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const store = useStore();
    const router = useRouter();
    
    // 表单数据
    const form = reactive({
      amount: '',
      projectName: '',
      profession: ''
    });
    
    // 投资数据
    const investment = ref(null);
    
    // 状态
    const loading = computed(() => store.getters.isLoading);
    const error = computed(() => store.getters.errorMessage);
    const submitting = ref(false);
    const transactionSuccess = ref(false);
    const transactionHash = ref('');
    const blockNumber = ref('');
    
    // 表单验证
    const isFormValid = computed(() => {
      return form.amount && 
             form.amount > 0 && 
             form.projectName && 
             form.profession && 
             (
               form.amount != investment.value?.amount ||
               form.projectName != investment.value?.projectName ||
               form.profession != investment.value?.profession
             );
    });
    
    // 加载投资详情
    const fetchInvestment = async () => {
      const result = await store.dispatch('fetchInvestmentById', props.id);
      if (result) {
        investment.value = result;
        
        // 填充表单
        form.amount = result.amount;
        form.projectName = result.projectName;
        form.profession = result.profession;
      }
    };
    
    // 提交表单
    const submitForm = async () => {
      if (!isFormValid.value) return;
      
      submitting.value = true;
      
      try {
        const investmentData = {
          amount: form.amount.toString(),
          projectName: form.projectName,
          profession: form.profession
        };
        
        const result = await store.dispatch('updateInvestment', {
          id: props.id,
          investmentData
        });
        
        if (result) {
          transactionSuccess.value = true;
          
          // 获取最新的交易哈希
          const events = store.getters.allEvents;
          const updateEvent = events.find(e => e.type === 'update' && e.id == props.id);
          if (updateEvent) {
            transactionHash.value = updateEvent.txHash;
            blockNumber.value = updateEvent.blockNumber;
          }
        }
      } catch (err) {
        console.error('更新投资失败:', err);
      } finally {
        submitting.value = false;
      }
    };
    
    // 组件挂载时加载投资详情
    onMounted(fetchInvestment);
    
    return {
      form,
      investment,
      loading,
      error,
      submitting,
      isFormValid,
      transactionSuccess,
      transactionHash,
      blockNumber,
      submitForm
    };
  }
}
</script>

<style scoped>
.card {
  max-width: 800px;
  margin: 0 auto;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style> 